<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室1</title>
</head>
<body>
<div style="text-align: center;background-color: rgba(129,86,255,0.35);margin:0 auto;border:1px solid #000;width:600px;height:650px">
    <br>欢迎使用<strong>陈本布衣</strong>牌极简聊天室：<br/><br/>
    <textarea id="content" cols="60" rows="30" readonly="readonly"></textarea>
    <br>
    <input type="text" id="sendMsg">
    <button type="button" onclick="sendMsg()">发送消息</button>
    <br/><br/>
    用户：<input type="text" id="user">
    <button onclick="joinRoom()">加入群聊</button>
    <button onclick="exitRoom()">退出群聊</button>
</div>
</body>
</html>

<script>
    // var url = "ws://127.0.0.1:8888/webSocket?userName=";
    var token = 'ea4aead8-2373-406e-98d0-c82856802e63'

    var url = 'ws://127.0.0.1:8090/v1/app/ws?SAAS-TOKEN=' + token;

    var ws = null;

    //加入聊天室
    function joinRoom() {
        if (ws) {
            console.log("你已经在聊天室，不能再加入");
            return;
        }
        // var username = document.getElementById("user").value;
        ws = new WebSocket(url + "&userName=12345678");

        //与服务端建立连接触发
        ws.onopen = function () {
            console.log("与服务器成功建立连接")
        };

        //服务端推送消息触发
        ws.onmessage = function (ev) {
            document.getElementById("content").append(ev.data + "\r\n");
        };

        //发生错误触发
        ws.onerror = function () {
            console.log("连接错误")
        };

        //正常关闭触发
        ws.onclose = function () {
            console.log("连接关闭");
        };
    }

    //退出聊天室
    function exitRoom() {
        if (ws) {
            ws.close();
            ws = null;
        }
    }

    function sendMsg() {
        if (!ws) {
            alert("你已掉线，请重新加入");
            return;
        }
        //消息发送
        ws.send(document.getElementById("sendMsg").value);
        document.getElementById("sendMsg").value = "";
    }
</script>